<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ include file="blocks/header.jsp" %>

<div class="row" id="listingsDiv">
	<div class="span4">
		
		
        <div class="row">
            <h4 class="span3 well">Условия&#32;поиска</h4>
            <div class="span3 well">
                <%@ include file="forms/mainFindForm.jsp" %>
            </div>
        </div>


<script type="text/javascript">
    $(function(){

        var AnnouncementsCollection = Backbone.Collection.extend({
            model: Announcement,
            initialize: function(){
                this.comparatorType = "price";
                this.findRequest = null;
            },
            getComparatorType: function() {
                return this.comparatorType;
            },
            setComparatorType: function(comparatorType) {
                this.comparatorType = comparatorType;
            },
            _createModel: function(inJson) {
                var realty = new Realty(inJson['realty']);
                inJson['realty'] = realty;
                var announcement = new Announcement(inJson);
                return announcement;
            },
            loadData: function(data) {
                this.findRequest = data;
                $.loadingBlock("findAnnouncements", "show");
                this.reset();
                var self = this;
                $.ajax({
                    type: "POST",
                    url: "<c:url value='/api/findAnnouncements.json' />",
                    dataType : "json",
                    data: JSON.stringify(data),
                    contentType: "application/json",
                    success: function (data, textStatus) {
                        console.log("out data(/api/findAnnouncements.json):");
                        console.log(data);
                        for (var i in data) {
                            data[i] = self._createModel(data[i]);
                        }
                        self.add(data);
                        $.loadingBlock("findAnnouncements", "hide");
                    }
                });
            },
            comparator: function(inObj) {
                switch (this.comparatorType) {
                    case "rank":
                        return -inObj.get('rating');
                        break;
                    case "price":
                        return inObj.get('price');
                        break;
                    case "-price":
                        return -inObj.get('price');
                        break;
                }
            }
        });

        announcementsCollection = new AnnouncementsCollection();

        var ListRealtyController = Backbone.Router.extend({
            initialize: function() {
                /*var findRequest = jQuery.parseJSON('${findRequest}');
                if (findRequest) {
                    console.log(findRequest);
                    exports.findRealtyView.setDataOnFrom(findRequest);
                    this.findRealty(findRequest);
                }*/
            },
            findRealty: function(findRequest) {
                announcementsCollection.loadData(findRequest);
                listRealtyView.setPage(findRequest.page ? findRequest.page : 0);
                // изменяем хеш, но не выполняем обработчик (тригер)
                this.navigateFindRequest(findRequest);
                //this.navigate("findRealty/type=" + findRequest.type + "/operation=" + findRequest.operation + "/adress=" +
                //        findRequest.adress + "/priceFrom=" + findRequest.priceFrom + "/priceTo=" + findRequest.priceTo + "/page=" + findRequest.page, {trigger: false, replace: true});
            },
            navigateFindRequest: function(findRequest) {
                this.navigate("findRealty/type=" + findRequest.type + "/operation=" + findRequest.operation + "/adress=" +
                        escape(findRequest.adress) + "/priceFrom=" + findRequest.priceFrom + "/priceTo=" + findRequest.priceTo + "/page=" + findRequest.page, {trigger: false, replace: false});
            }
        });

        var Realty = Backbone.Model.extend({
            defaults:{
                "id":3,
                "type":"",
                "description":"",
                "adress":"",
                "level":5,
                "levelsBuilding":5,
                "numberRooms":1,
                "area":566.0
            }
        });

        var Announcement = Backbone.Model.extend({
            defaults:{"id":2,
                "price":5666.0,
                "status":true,
                "datePublication":1359920680000
            }
        });

        var ListRealtyView = Backbone.View.extend({
            initialize: function(){
                this.page = 1;
                this.itemsOnPage = 3;
                this.collection.bind("reset", this.update, this);
                this.collection.bind("add", this.update, this);
                this.$el.find("#sort option[value='" + this.collection.getComparatorType() +"']").prop("selected", true);
                //this.collection.getComparatorType();
            },
            events: {
                "click .linkToPage": function (ev) {
                    this.setPage($(ev.currentTarget).data("number-page"));
                    ev.preventDefault();
                },
                "click #linkToPrevPage": function (ev) {
                    if (this.getPage() != 1) {
                        this.setPage(this.getPage() - 1);
                    }
                    ev.preventDefault();
                },
                "click #linkToNextPage": function (ev) {
                    if (Math.ceil(this.collection.models.length / this.itemsOnPage) > this.getPage()) {
                        this.setPage(this.getPage() + 1);
                    }
                    ev.preventDefault();
                },
                "change #sort": function() {
                    this.collection.setComparatorType($("#sort option:selected").val());
                    this.collection.sort();
                }
            },
            setPage: function (page) {
                this.page = page;
                this.update();
                this.collection.findRequest.page = page;
                listRealtyController.navigateFindRequest(this.collection.findRequest);
            },
            getPage: function() {
                return this.page;
            },
            update: function() {
                var startIndexItem = (this.page - 1) * this.itemsOnPage;
                var endIndexItem = (this.page * this.itemsOnPage) - 1;
                if (this.collection.models.length != 0) {
                    var endItemIndexOnPage = startIndexItem  +  this.itemsOnPage;
                    if (this.collection.models.length - this.itemsOnPage * this.page < 0) {
                        endItemIndexOnPage = startIndexItem + this.collection.models.length - this.itemsOnPage * (this.page - 1);
                    }
                    this.$el.find("#intervalFindResults").html((startIndexItem + 1) + " - " + endItemIndexOnPage);
                } else {
                    this.$el.find("#intervalFindResults").html('0 - 0');
                }
                this.$el.find("#maxFindResults").html(this.collection.models.length);
                // list announcements
                this.$el.find("#announcementsList").empty();
                console.log(this.collection.models);
                for (var i = startIndexItem; i <= endIndexItem; i++) {
                    if (this.collection.models[i]) {
                        this.$el.find("#announcementsList").append(
                            _.template($.getTemplate("announcementItem"), { announcement: this.collection.models[i] })
                        );
                    }
                }
                // list links on pages
                this.$el.find("#paginationUl").empty();
                if (Math.ceil(this.collection.models.length / this.itemsOnPage) > 1) {
                    this.$el.find("#paginationUl").append('<li><a href="#" id="linkToPrevPage">Назад</a></li>');
                    for (var i = 1; i <= Math.ceil(this.collection.models.length / this.itemsOnPage); i++) {
                        this.$el.find("#paginationUl").append('<li'+ ((i == this.page) ? ' class="active"' : '') + '><a href="#" class="linkToPage" data-number-page="' + i + '">' + i + '</a></li>');
                    }
                    this.$el.find("#paginationUl").append('<li><a href="#" id="linkToNextPage">Далее</a></li>');
                }
            }
        });

        listRealtyController = new ListRealtyController();
        listRealtyView = new ListRealtyView({
            collection: announcementsCollection,
            el: "#listingsDiv"
        });

    });
</script>

<div class="row">
<h4 class="span3 well">Фильтры</h4>
	<div class="span3 well">
		
		<h4>Property type:</h4>
		<ul class="nav">
			<li>
				<a class="active" href="category.html">Houses (12)</a>
				<ul>
					<li><a href="listings.html"> - Detached houses (11)</a></li>
					<li><a class="active" href="listings.html"> - Semi-detached houses (1)</a></li>
					<li><a class="active" href="listings.html"> - Terraced houses (1)</a></li>
				</ul>
			  </li>
			<li><a href="category.html">Bungalows (5)</a></li>
			<li><a href="category.html">Land (2)</a></li>
		</ul>	
		<h4>Preowned & new homes:</h4>
		<ul class="nav">	
			<li><a href="category.html">Pre-owned homes (5)</a></li>
			<li><a href="category.html">Brand new homes (2)</a></li>
		</ul>	
		<h4>Outside space:</h4>
		<ul class="nav">	
			<li><a href="category.html">Garden (5)</a></li>
			<li><a href="category.html">Parking (2)</a></li>
		</ul>

	</div>
</div>
<div class="row">
<h4 class="span3 well">Near London</h4>
	<div class="span3  well">
		
		<ul class="nav">
			<li><a href="category.html">Scotland</a></li>
			<li><a href="category.html">Wales</a></li>
			<li><a href="category.html">Northern Ireland</a></li>
			<li><a href="category.html">Birmingham</a></li>
			<li><a href="category.html">Leeds</a></li>
			<li><a href="category.html">Glasgow</a></li>
			<li><a href="category.html">Sheffield</a></li>
			<li><a href="category.html">Bradford</a></li>
			<li><a href="category.html">Edinburgh</a></li>
			<li><a href="category.html">Liverpool</a></li>
			<li><a href="category.html">Manchester</a></li>
		</ul>	

	</div>
</div>

<div class="row">
<h4 class="span3 well">Popular searches</h4>
	<div class="span3  well">
		
		<ul class="nav">
			<li><a href="category.html">Property for sale in London</a></li>
			<li><a href="category.html">Houses for sale in London</a></li>
			<li><a href="category.html">2 bedroom houses for sale in London</a></li>
			<li><a href="category.html">3 bedroom houses for sale in London</a></li>
			<li><a href="category.html">4 bedroom houses for sale in London</a></li>
			<li><a href="category.html">5+ bedroom houses for sale in London</a></li>
			<li><a href="category.html">Flats for sale in London</a></li>
			<li><a href="category.html">Studio flats for sale in London</a></li>
			<li><a href="category.html">1 bedroom flats for sale in London</a></li>
			<li><a href="category.html">2 bedroom flats for sale in London</a></li>
		</ul>	

	</div>
</div>	</div>
	
	<div class="span8">	
		
		
		<div class="row">
            <%@ include file="forms/mainFindForm.jsp" %>
		</div>
		
		<div class="row">
			<div class="span4 select_height">	Отображены <span id="intervalFindResults">0 - 0</span> из <span id="maxFindResults">0</span> найденых результатов</div>
			<div class="pull-right">
				Сортировать :
				<select id="sort" name="sort" class="span3">
					<option value="rank">По популярности</option>
					<option value="price">Цена: по возростанию</option>
					<option value="-price">Цена: по убыванию</option>
				</select>
			</div>
		</div>
		    <div id="announcementsList">

		    </div>
		</div>
		<hr />	  	
				
		
		
		<div class="pagination">
			<ul id="paginationUl">
			<!--	<li><a href="#">Prev</a></li>
				<li class="active">
					<a href="#">1</a>
				</li>
				<li><a href="#">2</a></li>
				<li><a href="#">3</a></li>
				<li><a href="#">4</a></li>
				<li><a href="#">5</a></li>
				<li><a href="#">6</a></li>
				<li><a href="#">7</a></li>
				<li><a href="#">8</a></li>
				<li><a href="#">9</a></li>
				<li><a href="#">10</a></li>
				<li><a href="#">Next</a></li>-->
			</ul>
		</div>
		
	</div>
	
</div>

<%@ include file="blocks/footer.jsp" %>